package vip.zhenzicheng.nettyadv;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.NettyRuntime;
import io.netty.util.concurrent.DefaultThreadFactory;
import vip.zhenzicheng.nettyadv.constant.NettyConstant;
import vip.zhenzicheng.nettyadv.server.ServerInit;

import java.util.logging.Logger;

/**
 * 服务端的主入口
 *
 * @author zhenzicheng
 * @date 2022-06-13 14:14
 */
public class NettyServer {

  private static final Logger LOG = Logger.getLogger(NettyServer.class.getSimpleName());

  public static void main(String[] args) throws InterruptedException {
    new NettyServer().bind();
  }

  public void bind() throws InterruptedException {
    // 配置服务端的 NIO 线程组
    EventLoopGroup bossGroup = new NioEventLoopGroup(1, new DefaultThreadFactory("boss"));
    EventLoopGroup workerGroup = new NioEventLoopGroup(NettyRuntime.availableProcessors(), new DefaultThreadFactory(
        "nt_worker"));

    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(bossGroup, workerGroup)
        .channel(NioServerSocketChannel.class)
        .option(ChannelOption.SO_BACKLOG, 1024)
        .childHandler(new ServerInit());

    // 绑定端口，同步等待成功
    bootstrap.bind(NettyConstant.SERVER_PORT).sync();
    LOG.info("Netty server start：" + (NettyConstant.SERVER_IP + ":" + NettyConstant.SERVER_PORT));
  }
}
